<template>
  <div class="CharacterVerification" :style="{'width' : width + 'px','height' : height + 'px'}" ref="CharacterVerification">
    <canvas
      @click="refresh"
      :width="width"
      :height="height"
      ref="verifyCanvas"
      :style="{ cursor: 'pointer' }"
    ></canvas>
  </div>
</template>

<script lang="ts">
import { isTSIndexedAccessType } from '@babel/types'
import { defineComponent, ref, onMounted } from 'vue'
let add:number
export default defineComponent({
name: 'CharacterVerification',
props: {
  width: {
    type: Number,
    default: 136
  },
  height: {
    type: Number,
    default: 42
  }
},
setup (props) {
  const code = ref('')
  const CharacterVerification = ref<HTMLDivElement | null>(null)
  const verifyCanvas = ref<HTMLCanvasElement | null>(null)
  // 生成验证码
  onMounted(() => {
    refresh()
  })
  let ctx
  let result :number
  const oprList = ['+' ,'-','*']
  const refresh = () => {
    code.value = ''
    if (verifyCanvas.value?.getContext) {
      ctx = verifyCanvas.value.getContext('2d') as CanvasRenderingContext2D
    } else {
      return
    }
    var index = randomNum(0,3)
    ctx.fillStyle = bagColor[index]
    ctx.fillRect(0, 0, props.width, props.height)
    ctx.font = 20 + 'px SimHei'
    ctx.fillStyle = txtColor[index]
    var txt1 = randomNum(10,20)
    var txt2 = randomNum(0,9)
    var opr = oprList[index]
    if(index == 0){
      result = txt1 + txt2
    } else if (index == 1){
      result = txt1 - txt2
    }else {
      result = txt1 * txt2
    }
    ctx.fillText(txt1.toString() , 20, 30)
    ctx.fillText(opr,44,30)
    ctx.fillText(txt2.toString() , 60, 30)
    ctx.fillText('=' , 80, 30)
    ctx.fillText('?' , 100, 30)
  }
  /** 生成一个随机色 **/
  const bagColor = ['rgb(240, 255, 255)','rgb(255, 255, 240)','rgb(255, 255, 240)']
  const txtColor = ['rgb(255, 153, 0)','rgb(153, 51, 102)','rgb(0, 102, 153)']
  /** 生成一个随机数 **/
  const randomNum = (min: number, max: number) => {
    return Math.floor(Math.random() * (max - min) + min)
  }
  /** 验证验证码 **/
  const validate = (iptCode: string) => {
    if (iptCode === result.toString()) {
      return true
    } else {
      refresh()
      return false
    }
  }
  return {
    CharacterVerification,
    verifyCanvas,
    refresh,
    validate
  }
}
})
</script>